package com.zero.server;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class ServerView extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private JTextArea textArea;

	public ServerView() {
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setSize(450, 560);
		setLocationRelativeTo(null); // 在屏幕中居中显示
		try {
			setIconImage(ImageIO.read(new File("res/Icon.jpg")));
		} catch (IOException e) {
			SwingUtilities.invokeLater(
					() -> JOptionPane.showMessageDialog(null, "读取图标文件出错", "错误", JOptionPane.ERROR_MESSAGE));
		}
		setTitle("服务器端");
		init();
		addListener();
		setVisible(true);
	}

	/**
	 * 初始化
	 */
	private void init() {
		JLabel lblTitle = new JLabel("多人聊天服务器");
		lblTitle.setFont(new Font("微软雅黑 Light", Font.BOLD, 20));
		lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblTitle.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(lblTitle, BorderLayout.NORTH);

		JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);

		textArea = new JTextArea();
		textArea.setEditable(false); // 设置为不可修改
		scrollPane.setViewportView(textArea);
	}

	/**
	 * 添加监听器
	 */
	private void addListener() {
		// 窗口关闭监听
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				int result = JOptionPane.showConfirmDialog(null, "这可是服务端\n确认退出？？？", "请确认",
						JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					System.exit(0);
				}
			}
		});
	}

	/**
	 * 用于向文本区域添加信息
	 * 
	 * @param msg
	 */
	public void setTextArea(String msg) {
		textArea.append(msg);
		textArea.setCaretPosition(textArea.getDocument().getLength()); // 设置滚动在最下面
	}
}
